const dragBox = document.createElement("div");
dragBox.style.position = "fixed";
dragBox.style.boxSizing = "border-box";
dragBox.style.border = "1px dashed red";
dragBox.style.display = "none";

export function mouseDownHandler(
  e: React.MouseEvent,
  config: any,
  layer: SVGSVGElement | null | undefined,
  cb: Function
) {
  if (layer) {
    const { x, y, width, height } = layer.getBoundingClientRect();
    dragBox.style.left = "0";
    dragBox.style.top = "0";
    dragBox.style.width = config.width + "px";
    dragBox.style.height = config.height + "px";
    dragBox.style.display = "none";
    document.body.appendChild(dragBox);
    document.onmousemove = (e: MouseEvent) => {
      dragBox.style.left = e.clientX - config.width / 2 + "px";
      dragBox.style.top = e.clientY - config.height / 2 + "px";
      if (
        e.clientX >= x &&
        e.clientX <= x + width &&
        e.clientY >= y &&
        e.clientY <= y + height
      ) {
        dragBox.style.display = "block";
      } else {
        dragBox.style.display = "none";
      }
    };
    document.onmouseup = (e) => {
      document.body.removeChild(dragBox);
      document.onmousemove = null;
      document.onmouseup = null;
      if (
        e.clientX >= x &&
        e.clientX <= x + width &&
        e.clientY >= y &&
        e.clientY <= y + height
      ) {
        cb({
          position: {
            x: e.clientX - x - config.width / 2,
            y: e.clientY - y - config.height / 2,
          },
          ...config,
        });
      }
    };
  } else {
    cb(null);
  }
}
